class Solution {
public:
    int m, n;
    int ret = 0;
    int dx[4] = { 0, 0, 1, -1 };
    int dy[4] = { 1, -1, 0, 0 };
    bool vis[21][21];
    int count = 0, path = 0;

    int uniquePathsIII(vector<vector<int>>& grid) {
        m = grid.size(), n = grid[0].size();

        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                if (grid[i][j] == 0)
                    count++;

        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                if (grid[i][j] == 1)
                    dfs(grid, i, j);

        return ret;
    }

    void dfs(vector<vector<int>>& grid, int i, int j)
    {
        if (grid[i][j] == 2 && path == count)
        {
            ret++;
            return;
        }

        for (int k = 0; k < 4; k++)
        {
            int x = i + dx[k], y = j + dy[k];
            if (x >= 0 && x < m && y >= 0 && y < n && (grid[x][y] == 0 || grid[x][y] == 2) && !vis[x][y])
            {
                if (grid[x][y] == 0)
                {
                    path++;
                    vis[x][y] = true;
                    dfs(grid, x, y);
                    vis[x][y] = false;
                    path--;
                }
                else
                {
                    vis[x][y] = true;
                    dfs(grid, x, y);
                    vis[x][y] = false;
                }
            }
        }
    }
};